package com.chujian.framework.web.interceptor;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.chujian.framework.auth.Accessor;
import com.chujian.framework.auth.AccessorHolder;
import com.chujian.framework.auth.SecurityConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：chujian
 * @since ：2020-08-13
 * 调用者Interceptor，从请求头中获取登录用户
 */
@Slf4j
public class AccessorHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessorHeader = request.getHeader(SecurityConst.ACCESSOR_HEADER);
        if (StringUtils.isNotEmpty(accessorHeader)) { // 存在登录用户
            String accessorStr = Base64.decodeStr(accessorHeader);
            Accessor accessor = JSON.parseObject(accessorStr, Accessor.class);
            AccessorHolder.setAccessor(accessor);
        } else {
            // 无登录用户
            AccessorHolder.clear();
        }
        return true;
    }
}
